package com.fzu.geometa.auth.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fzu.geometa.auth.model.po.User;
import com.fzu.geometa.auth.service.AuthService;
import com.fzu.geometa.common.exception.GeometaException;
import com.fzu.geometa.common.model.dto.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import static com.fzu.geometa.common.model.dto.RestResponse.success;
import static com.fzu.geometa.common.model.dto.RestResponse.validFail;

/**
 * @www.codesheep.cn
 * 20190312
 */
@RestController
public class JwtAuthController {

    @Autowired
    private AuthService authService;

    // 登录
    @RequestMapping(value = "/authentication/login", method = RequestMethod.POST)
    public RestResponse<String> createToken(String username, String password) throws AuthenticationException {
        String token;
        try {
            token = authService.login(username, password);
        } catch (GeometaException e) {
            return validFail(e.getMessage());
        }

        if (StringUtils.isBlank(token)) {
            return validFail();
        } else {
            return success(token,"登录成功");
        }
    }

    // 注册
    @RequestMapping(value = "/authentication/register", method = RequestMethod.POST)
    public User register(/**@RequestBody**/ User addedUser ) throws AuthenticationException {
        return authService.register(addedUser);
    }

}
